﻿#include "FormNote.h"
#include "DialogNew.h"

//#include <boost/shared_ptr.hpp>
#include <QtGui>

const QString FormNote::m_strRoot = "./data/note";

FormNote::FormNote(QWidget * parent, Qt::WFlags f): SubFrame(parent, f)
{
	QSplitter *pSplit = new QSplitter( this );
	pSplit->setOrientation(Qt::Horizontal);

	m_treeWidget = new QTreeWidget(pSplit);
	m_treeWidget->setMaximumWidth(200);
	m_treeWidget->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOn);

	m_textEdit = new QTextEdit(pSplit);
	//m_textEdit->setFont(QFont("宋体", 12, QFont::Normal));

	QVBoxLayout* layoutTop = new QVBoxLayout(this);
	layoutTop->addWidget(pSplit);

	m_treeWidget->setContextMenuPolicy ( Qt::CustomContextMenu);
	connect( m_treeWidget,
		SIGNAL( customContextMenuRequested (const QPoint &)), 
		this, 
		SLOT( showTreeMenu(const QPoint & ) ) );

	connect( m_treeWidget,
			 SIGNAL( itemClicked ( QTreeWidgetItem * , int )), 
			 this, 
			 SLOT( treeClicked(QTreeWidgetItem*, int ) ) ) ;

	QStringList headerLabels;
    headerLabels << tr("Components");
	m_treeWidget->setHeaderLabels(headerLabels);
	m_treeWidget->header()->hide();

	m_menuPop = new QMenu(this);
	QAction *act = m_menuPop->addAction(QIcon("./images/filenew.png"),tr("Create Note"));
	connect(act, SIGNAL(triggered()), this, SLOT(CreateNote()));
	act = m_menuPop->addAction(QIcon("./images/class.png"),tr("Create Catory"));
	connect(act, SIGNAL(triggered()), this, SLOT(CreateClass()));
	act = m_menuPop->addAction(QIcon("./images/delete.png"),tr("Delete"));
	connect(act, SIGNAL(triggered()), this, SLOT(RemoveNote()));

	connect( m_textEdit,
		SIGNAL( textChanged ()), 
		this, 
		SLOT( textChanged(void) ) ) ;

	m_strCurFileName = "";

	m_modified = false;

	refreshList();
}

FormNote::~FormNote(void)
{
	save();
}

void FormNote::showTreeMenu(const QPoint & pos)
{
	QPoint pg = m_treeWidget->mapToGlobal(pos);
	m_menuPop->exec(pg);
}
void FormNote::CreateNote()
{
	fileNew();
}
void FormNote::CreateClass()
{
	DialogNew dlg;
	dlg.exec();
	QString strD = dlg.m_textEdit->text();

	if(strD == "")
	{
		return;
	}

	QString path;
	if(m_strCurFileName == "" || m_strCurFileName.lastIndexOf(tr(".txt")) != -1)
	{
		path = FormNote::m_strRoot;
	}
	else
	{
		path = m_strCurFileName;
	}

	QDir dirRoot(path);
	//path = path + tr("/") + strD;
	if(!dirRoot.exists(strD))
	{
		dirRoot.mkdir(strD);
	}
	else
	{
		QMessageBox::warning(this, tr("hello"),
			tr("Catory already exists %1!")
			.arg(path));   
		return;
	}
	refreshList();
}
void FormNote::RemoveNote()
{
	fileDelete();
}

void FormNote::ShowDir(QTreeWidgetItem* pParent, const QString& path, QTreeWidget* pTree)
{
	QDir dir(path);
	QFileInfoList fileList = dir.entryInfoList();
	int size = fileList.size();
	//先显示目录
	for ( int i=0; i<size ; ++i)
	{
		if( (!fileList[i].isDir()) || fileList[i].fileName() == "." || fileList[i].fileName() == "..")
		{
			continue;
		}

		QTreeWidgetItem *it = NULL;

		if(NULL == pParent)
		{
			it = new QTreeWidgetItem(pTree);
		}
		else
		{
			it = new QTreeWidgetItem(pParent);
		}

		it->setIcon(0,QIcon("./images/class.png"));
		ShowDir(it, fileList[i].filePath(), pTree);
		it->setText(0,fileList[i].baseName());
		it->setData(0, Qt::UserRole, dir.filePath(fileList[i].fileName()));
	}
	//再显示文件
	for ( int i=0; i<size ; ++i)
	{
		if(fileList[i].isDir() || fileList[i].fileName() == "." || fileList[i].fileName() == "..")
		{
			continue;
		}

		QTreeWidgetItem *it = NULL;

		if(NULL == pParent)
		{
			it = new QTreeWidgetItem(pTree);
		}
		else
		{
			it = new QTreeWidgetItem(pParent);
		}

		it->setIcon(0,QIcon("./images/files.png"));
		it->setText(0,fileList[i].baseName());
		it->setData(0, Qt::UserRole, dir.filePath(fileList[i].fileName()));
		if(m_strCurFileName == dir.filePath(fileList[i].fileName()))
		{
			pTree->setItemSelected(it, true);
			if(NULL != pParent)
			{
				QTreeWidgetItem* tmp = pParent;
				while(tmp)
				{
					pTree->expandItem(tmp);
					tmp = tmp->parent();
				}
			}
		}
	}
}

void FormNote::refreshList(void)
{
	m_treeWidget->clear();
	ShowDir(NULL, FormNote::m_strRoot, m_treeWidget);
}

void FormNote::treeClicked(QTreeWidgetItem* item, int column)
{
	save();
	if(setCurFileName(item->data(0, Qt::UserRole).toString()))
	{
		loadFile();
	}
}

void FormNote::loadFile(void)
{
	if("" == m_strCurFileName)
	{
		return;
	}

	if(m_strCurFileName.lastIndexOf(tr(".txt")) == -1)
	{
		return;
	}

    QFile file(m_strCurFileName);
    if (!file.open(QFile::ReadOnly | QFile::Text)) {
        QMessageBox::warning(this, tr("hello"),
                             tr("Cannot read file %1:\n%2.")
                             .arg(m_strCurFileName)
                             .arg(file.errorString()));
        return;
    }

    QTextStream in(&file);
	in.setCodec(QTextCodec::codecForName("GB2312"));
    QApplication::setOverrideCursor(Qt::WaitCursor);
    m_textEdit->setPlainText(in.readAll());
    QApplication::restoreOverrideCursor();
	m_modified = false;
}

bool FormNote::setCurFileName(QString& name)
{
	if( m_strCurFileName == name )
	{
		return false;
	}
	else
	{
		 m_strCurFileName = name;
		 return true;
	}
}

void FormNote::fileNew(void)
{
	if(m_strCurFileName == "" || m_strCurFileName.lastIndexOf(tr(".txt")) != -1)
	{
		return;
	}

	DialogNew dlg;
	dlg.exec();
	QString strD = dlg.m_textEdit->text();

	if(strD == "")
	{
		return;
	}

	QDir yDir(m_strCurFileName);
	strD += tr(".txt");
	QString name = yDir.filePath(strD);
	if(!yDir.exists(strD ))
	{
		QFile file(name);
		file.open(QFile::WriteOnly | QFile::Text);
		file.close();
	}
	else
	{
      QMessageBox::warning(this, tr("hello"),
                             tr("File already exists %1!")
                             .arg(name));   
	  return;
	}

	m_strCurFileName = name;

	refreshList();

	loadFile();
}

void FormNote::save(void)
{
	if(!m_modified)
	{
		return;
	}
	if(m_strCurFileName.lastIndexOf(tr(".txt")) == -1)
	{
		return;
	}

	if(m_strCurFileName == "")
	{
		return;
	}
    QFile file(m_strCurFileName);
    if (!file.open(QFile::WriteOnly | QFile::Text)) {
        QMessageBox::warning(this, tr("hello"),
                             tr("Cannot write file %1:\n%2.")
                             .arg(m_strCurFileName)
                             .arg(file.errorString()));
        return;
    }

    QTextStream out(&file);
	out.setCodec(QTextCodec::codecForName("GB2312"));
    QApplication::setOverrideCursor(Qt::WaitCursor);
    out << m_textEdit->toPlainText();
    QApplication::restoreOverrideCursor();
}

void FormNote::fileDelete(void)
{
	if(QMessageBox::question(this, tr("hello"),
				 tr("Really delete note %1?").arg(m_strCurFileName),
				 QMessageBox::Yes,
				 QMessageBox::No) == QMessageBox::No)
	{
		return;
	}

	QDir dir(".");
	bool ret = false;

	if(m_strCurFileName.lastIndexOf(tr(".txt")) == -1)
	{
		ret = dir.rmdir(m_strCurFileName);
	}
	else
	{
		ret = dir.remove(m_strCurFileName);
	}

	if(!ret)
	{
        QMessageBox::warning(this, tr("hello"),
                             tr("Fail to deltet file %1!")
                             .arg(m_strCurFileName));
		return;
	}
	refreshList();

	m_strCurFileName = "";
}

void FormNote::textChanged(void)
{
	m_modified = true;
}
